package com.orm.analysis.dao.impl;

import com.orm.analysis.dao.GenericJPADAO;
import com.orm.analysis.model.Address;
import com.orm.analysis.model.Item;
import com.orm.analysis.model.OrderDetail;
import com.orm.analysis.model.Supplier;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Query;
import java.util.Arrays;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: saman
 * Date: 10/13/13
 * Time: 10:30 AM
 * To change this template use File | Settings | File Templates.
 */
public class ItemDAO extends GenericJPADAO<Item, Integer> {

       public List<Item> list(int page, int size) {
           Query query = this.em.createQuery("select a from Item a");
           query.setFirstResult((page - 1) * size);
           query.setMaxResults(size);
           return query.getResultList();
       }


       public Item getById(Integer id) {
             return this.em.find(Item.class,id);
       }

    @Transactional
           @Override
           public void save(Item entity) {

//        if (!getEntityManager().contains(entity)) {
//            for (Supplier supplier : entity.getSuppliers()) {
//
//                if (!getEntityManager().contains(supplier)) {
//                    getEntityManager().persist(supplier);
//                } else {
//                    getEntityManager().merge(supplier);
//                }
//            }

            getEntityManager().persist(entity);

//        } else {
//            getEntityManager().merge(entity);
//        }

    }


    @Transactional
                @Override
                    public void delete(Object id) {
                        getEntityManager().remove(getEntityManager().find(Item.class, id));

                     }

    public List<Item> findByIdList(Integer[] entityIdList){

           Query query = this.em.createQuery("select a from Item a  where a.itemId in (:entityIdList)");
           query.setParameter("entityIdList", Arrays.asList(entityIdList));
           return query.getResultList();
       }

    public List<Integer> findIdList() {
            Query query = this.em.createQuery("select  a.itemId  from Item a ");
            return query.getResultList();
        }
}
